package com.jake.xpage.page;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.view.animation.DecelerateInterpolator;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class XSlidePageAnimator implements IPageAnimator {
    ValueAnimator animator = ValueAnimator.ofFloat(0, 1);

    @Override
    public void start(@NonNull Type type, @NonNull XPage frontPage, @Nullable XPage backPage, @NonNull OnAnimateListener listener) {
        animator.removeAllListeners();
        animator.removeAllUpdateListeners();
        if (animator.isRunning()) {
            animator.cancel();
        }
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                listener.onStart();
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                frontPage.setTranslationX(0);
                if (backPage != null) {
                    backPage.setTranslationX(0);
                }
                listener.onEnd();
            }
        });
        animator.setInterpolator(new DecelerateInterpolator());
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                int width = frontPage.getWidth();
                if (width <= 0 && backPage != null) {
                    width = backPage.getWidth();
                }
                if (type == Type.PUSH) {
                    frontPage.setTranslationX(width * (1 - value));
                    if (backPage != null && !frontPage.pageInfo.transparent) {
                        backPage.setTranslationX(width / 2f * (-value));
                    }
                } else {
                    frontPage.setTranslationX(width * value);
                    if (backPage != null && !frontPage.pageInfo.transparent) {
                        backPage.setTranslationX(width / 2f * (value - 1));
                    }
                }
            }
        });

        animator.start();
    }
}
